import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/view/Login/index.vue')
    },
    {
      path: '/',
      component: () => import('@/view/Layout/index.vue'),
      redirect: '/home',
      children: [
        {
          path: '/home',
          component: () => import('@/view/Home/index.vue')
        },
        {
          path: '/user',
          component: () => import('@/view/User/index.vue')
        },
        {
          path: '/scenic',
          component: () => import('@/view/Scenic/index.vue')
        },
        {
          path: '/community',
          component: () => import('@/view/Community/index.vue')
        }
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      component: () => import('@/view/ErrorPage/404.vue')
    }
  ]
})

// 访问权限控制
router.beforeEach(to => {
  const wihteList = ['/login']
  const token = localStorage.getItem('token')

  // 如果没有token并且不在白名单中，跳转到登录页
  if (!token && !wihteList.includes(to.path)) return '/login'
  // 如果已经登录了，访问登录页，跳转到首页
  if (token && to.path === '/login') return '/home'
})

export default router
